package lg.minecraft.plugin.testeconomy;

import lg.minecraft.plugin.testeconomy.command.ManiCommand;
import lg.minecraft.plugin.testeconomy.config.ManiConfig;
import lg.minecraft.plugin.testeconomy.storage.BaseStorage;
import lg.minecraft.plugin.testeconomy.storage.DataBaseStorage;
import lg.minecraft.plugin.testeconomy.storage.FileStorage;
import lg.minecraft.plugin.testeconomy.storage.model.*;
import lombok.Getter;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin;

import java.sql.SQLException;

public final class TestEconomy extends JavaPlugin {

    @Getter private static TestEconomy instance;
    @Getter private static ManiConfig maniConfig;

    private static BaseStorage storage;

    private static Placeholder placeholder;

    @Override
    public void onLoad() {
        instance = this;
        maniConfig = new ManiConfig();
        storage = getStorage();
        if (storage instanceof FileStorage) {
            ((FileStorage) storage).load();
        }
        Bukkit.getServicesManager().register(Economy.class, storage, this, ServicePriority.Highest);
    }

    @Override
    public void onEnable() {
        PluginCommand command = getCommand("TestEconomy");
        if (command == null) {
            getLogger().severe("无法注册命令");
        } else {
            command.setExecutor(new ManiCommand());
        }
        if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") == null) {
            getLogger().severe("无法加载 PlaceholderAPI 扩展");
        } else {
            placeholder = new Placeholder();
            placeholder.register();
        }
    }

    @Override
    public void onDisable() {
        if (storage != null) {
            if (storage instanceof DataBaseStorage) {
                try {
                    ((DataBaseStorage) storage).close();
                } catch (SQLException ignored) {}
            }
        }
        if (placeholder != null) {
            placeholder.unregister();
        }
    }

    @Override
    public void reloadConfig() {
        maniConfig.load();
    }

    public static BaseStorage getStorage() {
        if (storage != null) return storage;
        switch (maniConfig.getStorageType()) {
            default:
            case YAML: return new YAMLStorage();
            case JSON: return new JSONStorage();
            case XML: return new XMLStorage();
            case SQLITE: return new SQLiteStorage();
            case MYSQL: return new MySQLStorage();
        }
    }

}
